<style>
    .inventoryProductDetailForm-title {
        width: 100%;
        margin-left: 20px;
    }

    .inventoryProductDetailForm-title .title, .title {
        display: inline-block;
        font-size: 16px;
        font-weight: bold;
        color: #333333;
        line-height: 19px;
        position: relative;
        padding: 6px 0 19px 0;
    }

    .inventoryProductDetailForm-title .title:after, .title:after {
        content: '';
        display: block;
        position: absolute;
        left: 0;
        bottom: 0;
        width: calc(100% + 6px);
        height: 3px;
        background: #0A8B0A;
    }
    .import {
        opacity: 0;
        position: absolute;
        width: 69px;
        height: 38px;
        margin-left: -10px;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
                <div class="layui-form lay-header">
                    <div class="toolbar">
                        <div class="layui-form-item lay-query-content">
                            <div class="lay-query-box">
                                <div class="query-lt">

                                    <div class="layui-inline">
                                        <label class="layui-form-label w-auto">物料名称：</label>
                                        <div class="layui-input-inline mr0">
                                            <input name="skuName" class="layui-input" type="text"
                                                   placeholder="物料名称"/>
                                        </div>
                                    </div>


                                    <div class="layui-inline">
                                        <label class="layui-form-label w-auto">库位编码：</label>
                                        <div class="layui-input-inline mr0">
                                            <input name="shelfSpaceCode" class="layui-input" type="text"
                                                   placeholder="请输入库位编码"/>
                                        </div>
                                    </div>

                                    <div class="layui-inline">
                                        <label class="layui-form-label">仓库：</label>
                                        <div class="layui-input-inline mr0">
                                            <select id="warehouseId" name="warehouseId" lay-filter="warehouseId" lay-search
                                                    lay-verify=""></select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">库区：</label>
                                        <div class="layui-input-inline mr0">
                                            <select id="warehouseAreaId" name="warehouseAreaId" lay-filter="warehouseAreaId"
                                                    lay-search lay-verify=""></select>
                                        </div>
                                    </div>

                                    <div class="layui-inline">
                                        <label class="layui-form-label">货架：</label>
                                        <div class="layui-input-inline mr0">
                                            <select id="shelfId" name="shelfId" lay-search lay-verify="" ></select>
                                        </div>
                                    </div>




                                    <div class="layui-inline">
                                        <label class="layui-form-label w-auto">物料编码：</label>
                                        <div class="layui-input-inline mr0">
                                            <input name="skuCode" class="layui-input" type="text" autocomplete="off"
                                                   placeholder="物料编码"/>
                                        </div>
                                    </div>

                                </div>
                                <div class="query-rt">
                                    <div class="layui-inline">
                                        <button type="button" class="layui-btn icon-btn color-green"
                                                id="productInventorySearch" lay-filter="productInventorySearch"
                                                lay-submit>查询
                                        </button>
                                        <button type="reset" class="layui-btn icon-btn color-white" lay-filter="resets"
                                                lay-submit>重置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="lay-btn-rows">
                        <div class="lay-btn-box">
                            <div class="lay-btn-lt">
                                <button id="uploaderInputBtn" class="layui-btn icon-btn color-reseda">
                                    <input id="uploaderInput" type="file" name="file" class="import" accept=".xls,.xlsx"/>导入
                                </button>
                                <button id="productBtnExport" class="layui-btn icon-btn color-green">导出</button>
                            </div>
                            <div class="lay-btn-rt"></div>
                        </div>
                    </div>
                </div>
            <table class="layui-table" id="warehouseAreaSkuItermTable" lay-filter="warehouseAreaSkuItermTable"></table>
        </div>
    </div>
</div>

<!-- 表单弹窗 -->
<script type="text/html" id="workStationForm">
    <form lay-filter="workStationForm" class="layui-form model-form">
        <input name="id" type="hidden"/>

        <div class="layui-form-item">
            <label class="layui-form-label">物料名称：</label>
            <div class="layui-input-block">
                <input name="skuName"  placeholder="物料名称" type="text" class="layui-input" lay-verify="required"
                       required autocomplete="off"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">物料编码：</label>
            <div class="layui-input-block">
                <input name="skuCode" placeholder="物料编码" type="text" class="layui-input" lay-verify="required"
                       required autocomplete="off"/>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">备注：</label>
            <div class="layui-input-block">
                <input name="remark" placeholder="请输入备注" type="text" class="layui-input"/>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="workStationFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>


<!-- 表格操作列 -->
<script type="text/html" id="productInventoryTableBar">
   <!-- <a class="layui-btn layui-btn layui-btn-xs" lay-event="inventoryDistribution">库存分布</a> -->
  <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
</script>


<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin', 'laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var laydate = layui.laydate;
        var unitName;

        //仓库列表
        admin.initDataSelect("enterprisecab/warehouse/admin/warehouse/list", {limit: 9999}, "warehouseId", null, "仓库", null, null);
        //仓库选择事件
        form.on('select(warehouseId)', function (data) {
            $("#warehouseAreaId").empty();
            //仓库库区列表
            admin.initDataSelect("enterprisecab/warehouse/admin/warehouseArea/list", {
                limit: 9999,
                warehouseId: data.value
            }, "warehouseAreaId", null, "库区", null, null);
        });
        //仓库库区选择事件
        form.on('select(warehouseAreaId)', function (data) {
            $("#shelfId").empty();
            //库区货架列表
            admin.initDataSelect("enterprisecab/warehouse/admin/warehouseShelf/list", {
                limit: 9999,
                warehouseAreaId: data.value
            }, "shelfId", null, "库区货架", null, null);
        });


        // 渲染表格
        var insTb = table.render({
            elem: '#warehouseAreaSkuItermTable',
            url: config.base + 'enterprise/warehouseSkuIterm/admin/warehouseSkuIterm/list',
            page: true,
            limit: 10,
            limits: [5, 10, 20, 30, 40, 50, 60, 70, 80],
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers', title: "序号", width: 60}
                , {field: 'skuName', align: 'center', title: '物料名称'}
                , {field: 'skuCode', align: 'center', title: '物料编码'}
                , {field: 'skuSpec', align: 'center', title: '物料规格'}
                , {field: 'num', align: 'center', title: '数量'}
                , {field: 'warehouseName', align: 'center', title: '仓库'}
                , {field: 'warehouseAreaName', align: 'center', title: '库区'}
                , {field: 'shelfName', align: 'center', title: '货架'}
                , {field: 'shelfSpaceName', align: 'center', title: '库位'}
                , {field: 'shelfSpaceCode', align: 'center', title: '库位编码'}
                , {align: 'center', toolbar: '#productInventoryTableBar', title: '操作', width: 200}
            ]],
            done: function (res, curr, count) {
            }
        });
        form.render('select');

        // 工具条点击事件
        table.on('tool(warehouseAreaSkuItermTable)', function (obj) {
            var data = obj.data;

        });

        // 搜索
        form.on('submit(productInventorySearch)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
            return false;
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            $(".lay-query-box").find('select').val("");
            $(".lay-query-box").find('input').val("");
            xmSelect.get('#selectProductType')[0].setValue([])
            var field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
        });

        // 工具条点击事件
        table.on('tool(warehouseAreaSkuItermTable)', function (obj) {
            let data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data);
            }
        });

        function showEditModel(data) {
            admin.open({
                type: 1,
                area: '620px',
                offset: '65px',
                title:  '修改库位物料信息',
                content: $('#workStationForm').html(),
                success: function () {
                    if(data){
                        form.val('workStationForm', data);
                    }
                }
            });
        }


        // 表单提交事件
        form.on('submit(workStationFormSubmit)', function (d) {
            layer.load(2);
            admin.req('enterprise/warehouseSkuIterm/admin/warehouseSkuIterm/updateStockSkuInfo', JSON.stringify(d.field), function (res) {
                layer.closeAll('loading');
                if (res.code === 200) {
                    layer.msg(res.msg, {icon: 1});
                    table.reload('warehouseAreaSkuItermTable');
                    layer.closeAll('page');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, "PUT", true, 'application/json;charset=utf-8');
            return false;
        });



        $('#productBtnExport').click(function () {
            let skuName = $('#skuName1').val();
            let productTypeId = $('#productTypeId1').val();
            let skuCode = $('#skuCode1').val();
            let shelfId = $('#shelfId1').val();
            let warehouseAreaId = $('#warehouseAreaId1').val();
            let warehouseId = $('#warehouseId1').val();
            let shelfSpaceCode = $('#shelfSpaceCode1').val();


            // 创建一个对象来保存所有可能的查询参数
            let queryParams = {
                skuName: skuName,
                productTypeId: productTypeId,
                skuCode: skuCode,

                shelfId: shelfId,
                warehouseAreaId: warehouseAreaId,
                warehouseId: warehouseId,
                shelfSpaceCode: shelfSpaceCode

            };

            // 过滤掉值为 undefined 的属性
            queryParams = Object.keys(queryParams)
                .filter(key => queryParams[key] !== undefined && queryParams[key] !== '')
                .reduce((obj, key) => {
                    obj[key] = queryParams[key];
                    return obj;
                }, {});

            // 将过滤后的参数对象转换为查询字符串
            let queryString = new URLSearchParams(queryParams).toString();

            // 获取当前日期和时间
            let now = new Date();
            let year = now.getFullYear();
            let month = String(now.getMonth() + 1).padStart(2, '0'); // 注意：getMonth() 返回值是 0-11
            let day = String(now.getDate()).padStart(2, '0');
            let hour = String(now.getHours()).padStart(2, '0');
            let minute = String(now.getMinutes()).padStart(2, '0');
            let second = String(now.getSeconds()).padStart(2, '0');

            // 格式化日期和时间为 YYYYMMDD_HHMMSS 形式
            let formattedDateTime = `${year}${month}${day}_${hour}${minute}${second}`;

            // 设置下载文件名为 "产品数据_YYYYMMDD_HHMMSS.xls"
            let fileName = `产品库存数据_${formattedDateTime}.xls`;

            // 创建完整的URL，包括查询参数和文件名作为额外参数（如果后端支持的话）
            let fullUrl = config.base + 'enterprise/warehouseSkuIterm/admin/warehouseSkuIterm/export?' + queryString + '&fileName=' + encodeURIComponent(fileName);

            // 使用 window.open 打开新页面进行下载
            window.open(fullUrl + '&Authorization=Bearer ' + encodeURIComponent(config.getToken()), '_blank');
            // 注意：这里假设后端能够处理 fileName 参数，并根据它设置响应头中的 Content-Disposition 来指定下载文件名。
            // 如果后端不支持通过 URL 参数指定文件名，你可能需要调整后端代码来接受这种请求方式。
        });

        // 导入excel
        $("#uploaderInput").on("change", function (e) {
            layer.load(2);
            var formData = new FormData();
            var files = e.target.files;
            let that = $(this);
            formData.append("file", files[0]);
            formData.append("name", files[0].name); //这个地方可以传递多个参数
            $.ajax({
                url: config.base + "enterprise/warehouseSkuIterm/admin/warehouseSkuIterm/importExcel",
                data: formData,
                headers: { Authorization: "Bearer " + config.getToken() },
                type: "POST",
                processData: false,
                contentType: false,
                success: function (res) {
                    layer.closeAll("loading");
                    if (res.code == 200) {
                        layer.msg(res.msg, { icon: 1 });
                        layer.closeAll("page");
                        setTimeout((_) => {
                            location.reload();
                        }, 1000);
                    } else {
                        layer.msg(res.msg, { icon: 2 });
                    }
                    that.val("");
                },
            });
        });
        
    });
</script>